package main

import (
	"log"
	"reflect"
	"runtime"

	pg "gopkg.in/pg.v5"
)

type MyDB struct {
	Conn *pg.DB
}

func NewMyDB(addr, user, passwd, db string) *MyDB {
	var DBC = pg.Connect(&pg.Options{
		Addr:                  addr,
		User:                  user,
		Password:              passwd,
		Database:              db,
		PoolSize:              runtime.GOMAXPROCS(-1),
		RetryStatementTimeout: true,
	})
	if DBC == nil {
		log.Printf("数据库连接错误: %s\n", db)
		log.Fatal("数据库连接错误")
	}
	return &MyDB{DBC}
}

func (self *MyDB) Close() {
	self.Conn.Close()
}

func (self *MyDB) ExecSqls(sqls []string) error {
	db1 := self.Conn
	tx, err := db1.Begin()
	if err != nil {
		return err
	}
	for _, s := range sqls {
		_, err := tx.Exec(s)
		if err != nil {
			log.Println(err)
			return err
		}

	}
	return tx.Commit()
}

//GetCount:按照 count(clumn) 计算记录数量， cond_sql为from开始的后半段sql语句,例如"from table1 where id>?"
//格式： num = GetCount("列名","from 数据表名 where 条件，含有几个'?'",对应'?'的可变长度参数...)
func (self *MyDB) GetCount(clumn string, cond_sql string, args ...interface{}) int {
	var DBC = self.Conn
	var sql = "select count(?) " + cond_sql
	var res1 int
	var f reflect.Value = reflect.ValueOf(DBC.QueryOne)
	var arg []reflect.Value
	arg = make([]reflect.Value, len(args)+3)
	arg[0] = reflect.ValueOf(&res1)
	arg[1] = reflect.ValueOf(sql)
	arg[2] = reflect.ValueOf(clumn)
	for i := 0; i < len(args); i++ {
		if args[i] == nil {
			log.Println("error:GetCount refuse nil argument")
			return 0
		}
		arg[i+3] = reflect.ValueOf(args[i])
	}
	ret := f.Call(arg)
	if ret[1].Interface() != nil {
		err := ret[1].Interface().(error)
		log.Println(err)
		return 0
	}
	return res1
}
